package com.atguigu.edu.entity.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.edu.entity.EduSubject;
import com.atguigu.edu.service.EduSubjectService;
import com.atguigu.service.base.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Data
@NoArgsConstructor
public class SubjectReaderListener extends AnalysisEventListener<SubjectData> {
    public static final String ROOT_SUBJECT_ID = "0";
    private List<SubjectData> list = new ArrayList<>();

    private EduSubjectService eduSubjectService;

    public SubjectReaderListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (null == subjectData) {
            throw new GuliException(20001, "文件数据为空");
        }

        list.add(subjectData);

        // saveSubjectV2(subjectData);

        this.syncSubjectDataToDatabase(subjectData);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("读取完成");
    }



    /**
     * 根据表格行数据创建数据库记录
     * 因为父subject可能不存在,因此可能会创建多个subject(不同级别)
     * 树形结构可以通过迭代来创建
     * @param subjectData
     * @return
     */
    private Boolean syncSubjectDataToDatabase(SubjectData subjectData) {
        // List<String> subjectTitleList = this.getSubjectNameList(subjectData);
        List<String> subjectTitleList = subjectData.getFieldList();
        Iterator<String> iterator = subjectTitleList.iterator();
        EduSubject parentEduSubject = null;
        while (iterator.hasNext()) {
            String subjectTitle = iterator.next();
            EduSubject currentColumnEduSubject = this.getSubjectByTitleFromDatabase(subjectTitle);
            if (currentColumnEduSubject == null) {
                String title = subjectTitle;
                String pid = parentEduSubject == null ? ROOT_SUBJECT_ID : parentEduSubject.getId();
                EduSubject eduSubject = new EduSubject().setTitle(title).setParentId(pid);
                eduSubjectService.save(eduSubject);
            }
            currentColumnEduSubject = this.getSubjectByTitleFromDatabase(subjectTitle);
            parentEduSubject = currentColumnEduSubject;
        }
        return true;
    }

    private EduSubject getSubjectByTitleFromDatabase(String title) {
        return eduSubjectService.getOne(new QueryWrapper<EduSubject>().eq("title", title));
    }

    @Deprecated
    private List<String> getSubjectNameList(SubjectData subjectData) {
        String oneSubjectName = subjectData.getOneSubjectName();
        String twoSubjectName = subjectData.getTwoSubjectName();
        String thrSubjectName = subjectData.getThrSubjectName();
        ArrayList<String> fieldList = new ArrayList<>();
        fieldList.add(0, oneSubjectName);
        fieldList.add(1, twoSubjectName);
        fieldList.add(2, thrSubjectName);
        return fieldList;
    }










    @Deprecated
    private void saveSubjectV2(SubjectData subjectData) {
        String oneSubjectName = subjectData.getOneSubjectName();
        String twoSubjectName = subjectData.getTwoSubjectName();

        EduSubject oneEduSubject = getSubjectByTitleFromDatabase(oneSubjectName);
        if (oneEduSubject == null) {
            String title = oneSubjectName;
            String pid = "0";
            eduSubjectService.save(new EduSubject().setTitle(title).setParentId(pid));
            // 获取新建的一级分类 供后面的二级分类使用
            oneEduSubject = getSubjectByTitleFromDatabase(oneSubjectName);
        }

        EduSubject twoEduSubject = getSubjectByTitleFromDatabase(twoSubjectName);
        if (twoEduSubject == null) {
            String title = twoSubjectName;
            // 当前 subject 的 pid 为 上级 subject 的 id
            String pid = oneEduSubject.getId();
            eduSubjectService.save(new EduSubject().setTitle(title).setParentId(pid));
        }
    }

    /**
     * 根据 excel 文件读取的记录 添加数据库记录
     * @param subjectData
     */
    @Deprecated
    private void saveSubject(SubjectData subjectData) {
        // 如果一级分类不存在则添加一级分类, 一级分类的 parent_id = 0
        EduSubject oneEduSubject = this.existOneSubject(subjectData.getOneSubjectName());
        if (oneEduSubject == null) {
            EduSubject eduSubject = new EduSubject();
            eduSubject.setTitle(subjectData.getOneSubjectName()).setParentId("0");
            eduSubjectService.save(eduSubject);
        }

        // 添加二级分类
        // 已经判断一级分类存在, 从表格中获取一级分类id
        EduSubject twoEduSubject = this.existTwoSubject(subjectData.getTwoSubjectName(), oneEduSubject.getId());
        if (twoEduSubject == null) {
            EduSubject eduSubject = new EduSubject();
            eduSubject.setTitle(subjectData.getTwoSubjectName()).setParentId(oneEduSubject.getId());
            eduSubjectService.save(eduSubject);
        }
    }

    @Deprecated
    private EduSubject existOneSubject(String name) {
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("title", name)
                .eq("parent_id", 0);
        EduSubject result = eduSubjectService.getOne(queryWrapper);
        return result;
    }

    @Deprecated
    private EduSubject existTwoSubject(String name, String pid) {
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("title", name)
                .eq("parent_id", pid);
        EduSubject result = eduSubjectService.getOne(queryWrapper);
        return result;
    }
}
